package com.ruoyi.energy.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.energy.mapper.EmsEnergyReportMapper;
import com.ruoyi.energy.domain.EmsEnergyReport;
import com.ruoyi.energy.service.IEmsEnergyReportService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;

/**
 * 能源报表Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-20
 */
@Service
public class EmsEnergyReportServiceImpl implements IEmsEnergyReportService {
    
    @Autowired
    private EmsEnergyReportMapper emsEnergyReportMapper;

    /**
     * 查询能源报表列表
     * 
     * @param emsEnergyReport 能源报表
     * @return 能源报表
     */
    @Override
    public List<EmsEnergyReport> selectEmsEnergyReportList(EmsEnergyReport emsEnergyReport) {
        return emsEnergyReportMapper.selectEmsEnergyReportList(emsEnergyReport);
    }

    /**
     * 新增能源报表
     * 
     * @param emsEnergyReport 能源报表
     * @return 结果
     */
    @Override
    public int insertEmsEnergyReport(EmsEnergyReport emsEnergyReport) {
        validateReportData(emsEnergyReport);
        return emsEnergyReportMapper.insertEmsEnergyReport(emsEnergyReport);
    }

    /**
     * 修改能源报表
     * 
     * @param emsEnergyReport 能源报表
     * @return 结果
     */
    @Override
    public int updateEmsEnergyReport(EmsEnergyReport emsEnergyReport) {
        validateReportData(emsEnergyReport);
        return emsEnergyReportMapper.updateEmsEnergyReport(emsEnergyReport);
    }

    /**
     * 批量删除能源报表
     * 
     * @param reportIds 需要删除的能源报表主键
     * @return 结果
     */
    @Override
    public int deleteEmsEnergyReportByReportIds(Long[] reportIds) {
        return emsEnergyReportMapper.deleteEmsEnergyReportByReportIds(reportIds);
    }

    /**
     * 删除能源报表信息
     * 
     * @param reportId 能源报表主键
     * @return 结果
     */
    @Override
    public int deleteEmsEnergyReportByReportId(Long reportId) {
        return emsEnergyReportMapper.deleteEmsEnergyReportByReportId(reportId);
    }

    /**
     * 根据日期范围查询能源报表
     */
    @Override
    public List<EmsEnergyReport> selectEmsEnergyReportByDateRange(String startDate, String endDate, String reportType) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            throw new ServiceException("开始日期和结束日期不能为空");
        }
        return emsEnergyReportMapper.selectEmsEnergyReportByDateRange(startDate, endDate, reportType);
    }

    /**
     * 查询设备能耗趋势数据
     */
    @Override
    public List<EmsEnergyReport> selectEnergyTrendByDevice(Long deviceId, String reportType, Integer limit) {
        if (deviceId == null) {
            throw new ServiceException("设备ID不能为空");
        }
        if (limit == null) {
            limit = 30; // 默认查询30条
        }
        return emsEnergyReportMapper.selectEnergyTrendByDevice(deviceId, reportType, limit);
    }

    /**
     * 查询能耗排行榜
     */
    @Override
    public List<EmsEnergyReport> selectEnergyRanking(String reportType, String reportDate, Integer limit) {
        if (StringUtils.isEmpty(reportDate)) {
            reportDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        if (limit == null) {
            limit = 10; // 默认查询前10名
        }
        return emsEnergyReportMapper.selectEnergyRanking(reportType, reportDate, limit);
    }

    /**
     * 查询综合统计数据
     */
    @Override
    public Map<String, Object> selectComprehensiveStats(String reportType, String reportDate) {
        Map<String, Object> stats = new HashMap<>();
        
        // 查询总体能耗统计
        Map<String, Object> energyStats = emsEnergyReportMapper.selectTotalEnergyStats(reportType, reportDate);
        stats.put("energyStats", energyStats);
        
        // 查询设备运行状态统计
        Map<String, Object> runningStats = emsEnergyReportMapper.selectDeviceRunningStats(reportType, reportDate);
        stats.put("runningStats", runningStats);
        
        return stats;
    }

    /**
     * 生成报表数据
     */
    @Override
    public int generateReportData(String reportType, String reportDate) {
        if (StringUtils.isEmpty(reportType) || StringUtils.isEmpty(reportDate)) {
            throw new ServiceException("报表类型和统计日期不能为空");
        }
        
        // 验证报表类型
        if (!"1".equals(reportType) && !"2".equals(reportType) && !"3".equals(reportType) && !"4".equals(reportType)) {
            throw new ServiceException("报表类型无效，支持：1=日报，2=周报，3=月报，4=年报");
        }
        
        int result = 0;
        
        switch (reportType) {
            case "1": // 日报
                result = emsEnergyReportMapper.generateDailyReport(reportDate);
                break;
            case "3": // 月报
                result = emsEnergyReportMapper.generateMonthlyReport(reportDate);
                break;
            case "4": // 年报
                result = emsEnergyReportMapper.generateYearlyReport(reportDate);
                break;
            default:
                throw new ServiceException("暂不支持该报表类型的自动生成");
        }
        
        return result;
    }

    /**
     * 查询仪表盘统计数据
     */
    @Override
    public Map<String, Object> selectDashboardStats() {
        Map<String, Object> dashboard = new HashMap<>();
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String thisMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        
        // 今日统计
        Map<String, Object> todayStats = emsEnergyReportMapper.selectTotalEnergyStats("1", today);
        dashboard.put("todayStats", todayStats);
        
        // 本月统计  
        Map<String, Object> monthStats = emsEnergyReportMapper.selectTotalEnergyStats("3", thisMonth);
        dashboard.put("monthStats", monthStats);
        
        // 今日运行状态
        Map<String, Object> todayRunning = emsEnergyReportMapper.selectDeviceRunningStats("1", today);
        dashboard.put("todayRunning", todayRunning);
        
        // 能耗排行榜（前5名）
        List<EmsEnergyReport> ranking = emsEnergyReportMapper.selectEnergyRanking("1", today, 5);
        dashboard.put("energyRanking", ranking);
        
        return dashboard;
    }

    /**
     * 验证报表数据
     */
    private void validateReportData(EmsEnergyReport report) {
        if (report.getDeviceId() == null) {
            throw new ServiceException("设备ID不能为空");
        }
        
        if (StringUtils.isEmpty(report.getReportType())) {
            throw new ServiceException("报表类型不能为空");
        }
        
        if (report.getReportDate() == null) {
            throw new ServiceException("统计日期不能为空");
        }
        
        // 验证报表类型
        String[] validTypes = {"1", "2", "3", "4"};
        boolean isValidType = false;
        for (String type : validTypes) {
            if (type.equals(report.getReportType())) {
                isValidType = true;
                break;
            }
        }
        if (!isValidType) {
            throw new ServiceException("报表类型无效，支持：1=日报，2=周报，3=月报，4=年报");
        }
        
        // 验证数值范围
        if (report.getTotalEnergy() != null && report.getTotalEnergy().compareTo(java.math.BigDecimal.ZERO) < 0) {
            throw new ServiceException("总能耗不能为负数");
        }
        
        if (report.getAvgPower() != null && report.getAvgPower().compareTo(java.math.BigDecimal.ZERO) < 0) {
            throw new ServiceException("平均功率不能为负数");
        }
        
        if (report.getFaultCount() != null && report.getFaultCount() < 0) {
            throw new ServiceException("故障次数不能为负数");
        }
        
        if (report.getRunHours() != null && report.getRunHours().compareTo(java.math.BigDecimal.ZERO) < 0) {
            throw new ServiceException("运行时长不能为负数");
        }
        
        if (report.getStopHours() != null && report.getStopHours().compareTo(java.math.BigDecimal.ZERO) < 0) {
            throw new ServiceException("停机时长不能为负数");
        }
    }
}